/**
 * 
 */
package com.geezdata.cps.cqrs.integration;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geezdata.cps.base.enums.ErrorCode;
import com.geezdata.cps.base.exceptions.MyException;
import com.geezdata.cps.base.utils.HttpClientUtil;

/**
 * @author sszheng
 * @param <V>
 * @date 创建时间：2018年3月6日 上午10:39:12
 *
 */
public abstract class BaseIntegrationService {
	private static Logger logger = LoggerFactory.getLogger(BaseIntegrationService.class);
	public <V> V doPost(String url, Map<String, Object> params, Class<V> targetClazz) {
		return doPost(url, params, targetClazz, false);
	};
	
	public <V> V doPost(String url, Map<String, Object> params, Class<V> targetClazz, Boolean fakeLogin) {
		String merchantName = getMethodName();
		String rspStr = null;
		try {
        	rspStr = HttpClientUtil.post(url, params, fakeLogin);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        	return null;
        }
		
		if (rspStr == null) {
			logger.info( merchantName + " url {}", url);
        	logger.info( merchantName + " params {}", JSON.toJSONString(params));
        	throw new MyException(ErrorCode.INTERNAL_SERVER_ERROR.getCode(), merchantName + " failed "); 
		}
		
		JSONObject jsonObject = JSONObject.parseObject(rspStr);
		V result = JSONObject.toJavaObject(jsonObject.getJSONObject("result"), targetClazz);
		return result;	
	};
	
	private String getMethodName() {  
        StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();  
        StackTraceElement e = stacktrace[3];  
        String methodName = e.getMethodName();  
        return methodName;  
    }  
}
